package com.spark.gaea.utils;

import org.apache.commons.lang3.StringUtils;

public final class CodeUtil {
	public static final int CODE_LENGTH = 4;

	private static String getZeroCode(int length) {
		String fix = "";
		while (length > 0) {
			fix += "0";
			--length;
		}
		return fix;
	}

	public static String getFirstCode(final String superCode) {
		return getFirstCode(superCode, 4);
	}

	public static String getFirstCode(final String superCode, final int length) {
		if (StringUtils.isNotBlank(superCode)) {
			return getNextCode(superCode + "-" + getZeroCode(length), length);
		}
		return getNextCode(getZeroCode(length), length);
	}

	public static String getNextCode(final String code) {
		return getNextCode(code, 4);
	}

	public static String getNextCode(final String code, final int length) {
		final StringBuilder sb = new StringBuilder();
		final String[] codeSplit = code.split("-");
		final String lastCode = codeSplit[codeSplit.length - 1];
		final Integer lastNumber = Integer.parseInt(lastCode) + 1;
		String nextLastCode = getZeroCode(length) + lastNumber;
		nextLastCode = nextLastCode.substring(nextLastCode.length() - length);
		for (int i = 0, arrayLength = codeSplit.length - 1; i < arrayLength; ++i) {
			sb.append(codeSplit[i]);
			sb.append("-");
		}
		sb.append(nextLastCode);
		return sb.toString();
	}

	public static String fixCode(final String code) {
		return fixCode(code, 4);
	}

	public static String fixCode(final String code, final int length) {
		final String s = getZeroCode(length) + code;
		return s.substring(code.length());
	}
}
